package com.lagou.subjectfour;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {
    public static void main(String[] args) {
        //定义基本信息
        Socket s = null;
        Scanner sc = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            //服务器的主机名和端口号
            s = new Socket("127.0.0.1", 8888);
            sc = new Scanner(System.in);

            //输入信息
            System.out.print("输入用户名：");
            String name = sc.next();
            System.out.print("输入密码：");
            String password = sc.next();

            //发送信息
            oos = new ObjectOutputStream(s.getOutputStream());
            oos.writeObject(new UserMessage(new User(name, password), "Check"));

            //接受信息
            ois = new ObjectInputStream(s.getInputStream());
            Object obj = ois.readObject();
            //判断是不是UserMessage类的
            if (obj instanceof UserMessage) {
                //判断返回信息做展示
                UserMessage user = (UserMessage) obj;
                if ("success".equals(user.getType())) {
                    System.out.println("登陆成功！");
                } else {
                    System.out.println("登陆失败！");
                }
            } else
                System.out.println((String) obj);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //region 关闭一系列处理
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != sc)
                sc.close();
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //endregion

        }


    }
}
